package cn.dankal.flyaudio.personal

import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.graphics.Bitmap
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import android.view.View
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import api.UserServiceFactory
import butterknife.OnClick
import cn.dankal.basiclib.DKUserManager
import cn.dankal.basiclib.DankalApplication
import cn.dankal.basiclib.GlideApp
import cn.dankal.basiclib.base.activity.BaseActivity
import cn.dankal.basiclib.common.camera.CameraHandlerTow
import cn.dankal.basiclib.common.qiniu.UploadListener
import cn.dankal.basiclib.common.upload.ali.AliUIDisplayer
import cn.dankal.basiclib.common.upload.ali.AliUploadHelper
import cn.dankal.basiclib.protocol.LoginProtocol
import cn.dankal.basiclib.rx.AbstractDialogSubscriber
import cn.dankal.basiclib.template.personal.ChangeAvatar
import cn.dankal.basiclib.template.personal.ChangeAvatarImpl
import cn.dankal.basiclib.util.*
import cn.dankal.basiclib.util.image.PicUtils
import cn.dankal.basiclib.widget.TipDialog
import cn.dankal.business.eventbus.MessageUpdatePersonEvent
import cn.dankal.business.pojo.ReasonBean
import cn.dankal.flyaudio.R
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.request.target.BitmapImageViewTarget
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.entity.LocalMedia
import kotlinx.android.synthetic.main.activity_base_info.*
import org.greenrobot.eventbus.EventBus
import java.io.File


class BaseInfoActivity : BaseActivity() {
    val SETNAME_REQUESTCODE = 205
    lateinit var changeAvatar: ChangeAvatar

    lateinit var builder: TipDialog.Builder
    var uploadListener: UploadListener? = null
    var mUploadHelper: AliUploadHelper? = null
    override fun getLayoutId(): Int {
        return R.layout.activity_base_info
    }

    override fun initComponents() {
        addSingleTitleBar("基本信息")
        val userInfo = DKUserManager.getUserInfo()
        tv_nickname.text = userInfo.name
        tv_mobile.text = userInfo.phone
        tv_email.text = userInfo.email
        //todo email
//        tv_email.setText(userInfo.region)
        PicUtils.loadAvatar(userInfo.avatar, iv_head)
        changeAvatar = ChangeAvatarImpl(this, this)
        changeAvatar.setIvHead(iv_head)
        uploadListener = object : UploadListener {
            override fun onSucess(localPath: String, key: String) {
                loadingDialog.dismiss()

                /*  val dialog = builder.setIconType(TipDialog.Builder.ICON_TYPE_SUCCESS)

                          .setTipWord("上传成功")
                          .create(2000)
                  dialog.show()
                  dialog.dismiss()*/

                //                String path = PicUtil.getUrl(key);
                //                Uri uri = Uri.fromFile(tempFile);
                //                getIvHead().setImageURI(uri);


                UserServiceFactory.changeAvatar(key)
                        .subscribe(object : AbstractDialogSubscriber<ReasonBean>(this@BaseInfoActivity) {
                            override fun onNext(reasonBean: ReasonBean) {
                                //PicUtils.loadAvatar(key, iv_head)
                            }
                        })
            }

            override fun onUpload(percent: Double) {
//                val df = DecimalFormat("#0.00")
//                builder.setTipWord(df.format(percent * 100) + "%").showProgress()
                builder.setTipWord(percent.toString() + "%").showProgress()
            }

            override fun onError(string: String) {
                ToastUtils.showLong(string)
                loadingDialog.dismiss()
                val dialog = builder.setIconType(TipDialog.Builder.ICON_TYPE_FAIL)
                        .setTipWord("上传失败")
                        .create(2000)
                dialog.show()
                dialog.dismiss()
            }
        }
    }


//    @OnClick(R.id.ll_head, R.id.ll_nickname, R.id.ll_mobile, R.id.ll_email_bind, R.id.ll_pwd_change)
//    fun onViewClicked(view: View) {
//        when (view.getId()) {
//            R.id.ll_head -> {
//                var aliUIDisplayer = AliUIDisplayer(iv_head, this, uploadListener)
//                mUploadHelper = AliUploadHelper(this, aliUIDisplayer)
//                changeAvatar.checkPermission(CameraHandlerTow(this))
//            }
//
//            R.id.ll_nickname -> {
//                EventBus.getDefault().post(MessageUpdatePersonEvent(null))
//                startActivityForResult(Intent(this, EditNameActivity::class.java), SETNAME_REQUESTCODE)
//            }
//            R.id.ll_mobile -> {
//                EventBus.getDefault().post(MessageUpdatePersonEvent(null))
//                if (StringUtil.isValid(DKUserManager.getUserInfo().phone)) {
//                    startActivity(Intent(this, ShowMobileActivity::class.java))
//                } else {
//                    ARouter.getInstance().build(LoginProtocol.UNBIND_BIND_PHONE).navigation()
//                }
//            }
//            R.id.ll_email_bind -> {
//                EventBus.getDefault().post(MessageUpdatePersonEvent(null))
//                var intent = Intent(this, EditEmailActivity::class.java)
//                intent.putExtra("email", tv_email.text.toString())
//                startActivity(intent)
//            }
//            R.id.ll_pwd_change -> {
//                EventBus.getDefault().post(MessageUpdatePersonEvent(null))
//                startActivity(Intent(this, ModifyPasswdActivity::class.java))
//            }
//        }
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        /* if (resultCode == RESULT_OK) {
             if (data == null) {//拍照
                 val takePath = CamerImageBean.getInstance().path
                 PicUtils.loadUriAvatar(takePath, iv_head)
                 EventBus.getDefault().post(MessageUpdatePersonEvent(takePath))
                 uploadPic(takePath)
             } else {
                 EventBus.getDefault().post(MessageUpdatePersonEvent(data?.data))
                 data?.let {
                     PicUtils.loadUriAvatar(data.data, iv_head)
                     when (requestCode) {
                         SETNAME_REQUESTCODE -> tv_nickname.setText(data.getStringExtra("编辑昵称"))
                         RequestCodes.TAKE_PHOTO -> {
                             val takePath = CamerImageBean.getInstance().path
                             uploadPic(takePath)
                         }
                         RequestCodes.PICK_PHOTO -> {
                             val pickpath = Uri.parse(ImagePathUtil.getImageAbsolutePath(this, data.data))
                             uploadPic(pickpath)
                         }
                     }
                 }
             }
         }*/
        /*if (data != null) {
            PicUtils.loadUriAvatar(data.data, iv_head)
        }*/
        data?.let {
            if (requestCode == SETNAME_REQUESTCODE) {
                tv_nickname.setText(data.getStringExtra("编辑昵称"))
                return
            }
        }

        // 图片、视频、音频选择结果回调
        val selectList = PictureSelector.obtainMultipleResult(data)
        // 例如 LocalMedia 里面返回三种path
        // 1.media.getPath(); 为原图path
        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
        // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
        if (selectList != null && selectList.size > 0) {
            setImage(selectList)
        }
    }

    private fun setImage(list: List<LocalMedia>) {
        val media = list[0]
        val mimeType = media.mimeType
        var path = ""
        if (media.isCut && !media.isCompressed) {
            // 裁剪过
            path = media.cutPath
        } else if (media.isCompressed || media.isCut && media.isCompressed) {
            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
            path = media.compressPath
        } else {
            // 原图
            path = media.path
        }
        // 图片
        if (media.isCompressed) {
            Log.i("compress image result:", (File(media.compressPath).length() / 1024).toString() + "k")
            Log.i("压缩地址::", media.compressPath)
        }

        Log.i("原图地址::", media.path)
        //int pictureType = PictureMimeType.isPictureType(media.getPictureType());
        if (media.isCut) {
            Log.i("裁剪地址::", media.cutPath)
        }
        try {
            //uploadImage = UIUtils.compressImage(UIUtils.getBitmapFromUrl(path, 200, 200))
            var uri: Uri? = Uri.parse(path)

            GlideApp.with(DankalApplication.getContext()).asBitmap().centerCrop().error(R.mipmap.pic_ill_4).load(path).into(object : BitmapImageViewTarget(iv_head) {
                override fun setResource(resource: Bitmap?) {
                    val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource)
                    circularBitmapDrawable.isCircular = true
                    iv_head.setImageDrawable(circularBitmapDrawable)
                }
            })
            //Glide.with(this).load(path).into(iv_head)
            uri?.let {
                // PicUtils.loadUriAvatar(it, iv_head)
                var event: MessageUpdatePersonEvent = MessageUpdatePersonEvent(it)
                event.setPath(path)
                EventBus.getDefault().post(event)
                uploadPic(it)
            }


        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    private fun getMediaUriFromPath(context: Context, path: String): Uri? {
        var mediaUri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        var cursor: Cursor = context.getContentResolver().query(mediaUri,
                null,
                MediaStore.Images.Media.DISPLAY_NAME + "= ?",
                arrayOf(path.substring(path.lastIndexOf("/") + 1)),
                null)


        var uri: Uri? = null
        if (cursor.moveToFirst()) {
            uri = ContentUris.withAppendedId(mediaUri,
                    cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        }
        cursor.close()
        return uri
    }

    private fun uploadPic(photoUris: Uri) {
        builder = TipDialog.Builder(this)
        loadingDialog = builder
                .setIconType(TipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在上传").create()
        loadingDialog.show()
        val b = UriUtils.getPath(this, photoUris) == null

        mUploadHelper?.uploadPic(uploadListener, if (b) photoUris.path else UriUtils.getPath(this, photoUris))

    }

}
